import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:atten_sys/activities/index.dart';
import 'package:atten_sys/entity/Entity.dart';
import 'package:atten_sys/utils/utils.dart';
import 'package:atten_sys/utils/http.dart';

class LoginWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new LoginState();
  }
}

class LoginState extends State<LoginWidget> {


  HttpUtil _http = HttpUtil.getInstance();

  SharedPreferences preferences;

  final _formKey = GlobalKey<FormState>();

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  //控制text的Controller
  TextEditingController _jobNumController;
  TextEditingController _passwordController;

  String _jobNumber, _password;
  bool _isObscure, _isChecked;
  Color _eyeColor;

  User _user;

  initParam() async {
    print('Enter initParam Function');
    preferences = await SharedPreferences.getInstance();
    setState(() {
      print('init 1 $_isChecked');
      print(preferences.getBool('isChecked'));
      _isChecked = preferences.getBool('isChecked') ?? false;
      print('init $_isChecked');
      _jobNumController.text = preferences.getString('JOBNUMBER');
      if (_isChecked) {
        _passwordController.text = preferences.getString('PASSWORD');
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _isObscure = true;
    _eyeColor = Colors.grey;
    _isChecked = false;
    _jobNumController = new TextEditingController();
    _passwordController = new TextEditingController();
    initParam();
  }

  @override
  Widget build(BuildContext context) {
    print('$_isChecked build');
    // TODO: implement build
    return Scaffold(
      key: _scaffoldKey,
      body: Form(
        key: _formKey,
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 20),
          children: <Widget>[
            SizedBox(
              height: kToolbarHeight, //高度为一个Appbar
            ),
            buildTitle(),
            buildTitleLine(),
            SizedBox(
              height: 70,
            ),
            buildJobNumberTextField(),
            SizedBox(
              height: 30,
            ),
            buildPasswordTextField(),
            buildRememberMeField(),
            SizedBox(
              height: 60,
            ),
            buildLoginButton(context),
          ],
        ),
      ),
    );
  }

  //创建一个登陆方法
  Future login(String jobNumber, String password) async {
     var data = await _http.post('/app/login',
       data: {"jobNumber": jobNumber, "password": password},
       context: context,
       scaffoldKey: _scaffoldKey
     );
    if (data['payload'] != null) {
      _user = new User.fromJson(data['payload']);
      preferences.setString('JOBNUMBER', jobNumber);
      if (_isChecked) {
        preferences.setString('PASSWORD', password);
      }
      preferences.setBool('isChecked', _isChecked);
      preferences.setString('Authorization', data['payload']['token']);
      preferences.setInt('UID', data['payload']['id']);
    }
    return data;
  }

  //创建登录标题
  Padding buildTitle() {
    return Padding(
      padding: EdgeInsets.all(8),
      child: Text(
        '登录',
        style: TextStyle(fontSize: 42, color: Colors.blue),
      ),
    );
  }

  //创建登录下的下划线
  Padding buildTitleLine() {
    return Padding(
      padding: EdgeInsets.only(left: 12, top: 4),
      child: Align(
        alignment: Alignment.bottomLeft,
        child: Container(
          color: Colors.blue,
          width: 75,
          height: 2,
        ),
      ),
    );
  }

  TextFormField buildJobNumberTextField() {
    return TextFormField(
      controller: _jobNumController,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.person),
        labelText: '工号',
      ),
      validator: (String value) {
        print('Enter the JobNumber validator');
        var reg = RegExp(r'^\d{8}$');
        if (!reg.hasMatch(value)) {
          return '请输入8位工号数字';
        }
      },
      onSaved: (String value) => _jobNumber = value,
    );
  }

  TextFormField buildPasswordTextField() {
    return TextFormField(
      controller: _passwordController,
      obscureText: _isObscure,
      decoration: InputDecoration(
          labelText: '密码',
          prefixIcon: Icon(Icons.lock),
          suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = _isObscure ? Colors.grey : Colors.blue;
                });
              })),
      validator: (String value) {
        print('Enter the Password validator');
        var reg = RegExp(r'^[a-z0-9]{6,12}$');
        if (!reg.hasMatch(value)) return '请输入正确的6-12位密码';
      },
      onSaved: (String value) => _password = value,
    );
  }

  Align buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45,
        width: 270,
        child: RaisedButton(
          color: Colors.blue,
          highlightColor: Colors.blue[700],
          colorBrightness: Brightness.dark,
          splashColor: Colors.grey,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          child: Text(
            '登录',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
          ),
          onPressed: () {
            print('Enter the onPressed function');
            if (_formKey.currentState.validate()) {
              //验证成功则保存数据
              _formKey.currentState.save();
              print('jobNumber = $_jobNumber, password = $_password');
              DialogUtil.createLoading(
                  context, '登陆中', login(_jobNumber, _password), (data) {
                if (data['payload'] != null) {
                  Navigator.pushAndRemoveUntil(context,
                      MaterialPageRoute(builder: (context) {
                    return Index(user: _user);
                  }), (route) => route == null);
                } else {
                  DialogUtil.createDialog(context, '错误', data['msg']);
                }
              });
            }
          },
        ),
      ),
    );
  }

  Row buildRememberMeField() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Checkbox(
            value: _isChecked,
            onChanged: (_) {
              setState(() {
                _isChecked = !_isChecked;
                print('isChecked = $_isChecked');
              });
            }),
        new Text('记住密码'),
      ],
    );
  }
}
